# -*-coding: Utf-8 -*-
# @File : convention .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2024/7/1
from django.http import JsonResponse
from rest_framework import status
import json
from django.core.serializers.json import DjangoJSONEncoder
from typing import Dict, Tuple, Optional, Any, Union


class CommonResponse(object):
    # 构造自定义的响应体数据
    response_data = {
        "code": '',
        "message": '',
        "data": {},
        "request_id": '',
        "success": True
    }

    def back(
            self,
            code: str,
            response_data,
            back_status,
            request_id: str = None,
            encoder=DjangoJSONEncoder,
            safe=True,
            json_dumps_params=None,
            **kwargs,
    ):
        '''
        :param code: 响应码
        :param response_data: 响应体数据
        :param back_status: 响应状态码 应该使用 rest_framework.status
        :param request_id: 请求ID
        :param encoder: 编码格式
        :param safe: 是否严格验证
        :param json_dumps_params: json序列化补充参数
        :param kwargs: 额外关键字参数
        '''
        self.response_data["code"] = code
        self.response_data["success"] = True if code == '1' else False
        self.response_data["request_id"] = request_id
        # 判断是否启用严格模式 并校验 传入的参数是否是字典格式
        if safe and not isinstance(self.response_data, dict):
            raise TypeError(
                "In order to allow non-dict objects to be serialized set the "
                "safe parameter to False."
            )
        # 判断是否存在多余的 json 校验参数
        if json_dumps_params is None:
            json_dumps_params = {}
        # 更新状态码到 关键字参数中
        kwargs.update({"status": back_status})
        # 调用父类方法 返回响应对象
        return JsonResponse(data=response_data,
                            encoder=encoder,
                            safe=safe,
                            json_dumps_params=json_dumps_params,
                            **kwargs)

    def success(self,
                code: str = '1',
                message: str = "请求成功!",
                data: Union[None, Dict[str, Any]] = None,
                back_status=status.HTTP_200_OK,
                request_id: str = None,
                **kwargs):
        '''
        :param code: 响应码
        :param message: 响应信息
        :param data: 响应数据
        :param back_status:
        :param request_id:
        :param kwargs:
        :return:
        '''
        # 【一】默认成功响应，响应成功，但是没有实体数据
        # 判断响应体数据是否为空 ， 为空则放入空字典
        if data is None:
            self.response_data["data"] = {}
        # 【二】构造成功响应，响应成功，并且有实体数据
        else:
            self.response_data["data"] = data
        # 如果有关键字参数更新到字典中
        if kwargs:
            self.response_data.update(**kwargs)
        self.response_data["message"] = message
        return self.back(code=code,
                         request_id=request_id,
                         response_data=self.response_data,
                         back_status=back_status,
                         **kwargs)

    def failure(self,
                code: str = None,
                message: str = None,
                request_id: str = None,
                back_status=status.HTTP_200_OK,
                **kwargs
                ):
        # 【一】服务端失败响应
        self.response_data["code"] = code
        self.response_data["message"] = message
        return self.back(code=code,
                         request_id=request_id,
                         response_data=self.response_data,
                         back_status=back_status,
                         **kwargs)
